import {
  RunnablePassthrough,
  RunnableSequence,
} from "@langchain/core/runnables";
import { PromptTemplate } from "@langchain/core/prompts";
import { ChatOllama } from "@langchain/ollama";
import { StringOutputParser } from "@langchain/core/output_parsers";

// 1. 记录日志
const logFunc = new RunnablePassthrough({
  func: async (input) => {
    // 做一些记录：上报、数据操作、埋点
    console.log("用户提的问题为：", input);
  },
});

// 2. 注入用户id
const injector = RunnablePassthrough.assign({
  userId: async () => "user-12345",
});

// 3. 提示词模板
const pt = PromptTemplate.fromTemplate(
  "请使用中文帮用户 {userId} 解答问题：{query}，回答问题时以亲爱的{userId}开头"
);

console.log(await injector.invoke(pt));

// 4. 模型
const model = new ChatOllama({
  model: "llama3",
  temperature: 0.7,
});

// 5. 解析器
const parser = new StringOutputParser();

// 6. 构建完整的链
const chain = RunnableSequence.from([logFunc, injector, pt, model, parser]);

const res = await chain.stream({
  query: "闭包是什么意思？",
});

for await (const chunk of res) {
  process.stdout.write(chunk);
}
